let App = getApp();
let wxParse = require("../../wxParse/wxParse.js");
var that;
// 最大行数
var max_row_height = 5;
// 行高
var cart_offset = 90;
// 底部栏偏移量
var food_row_height = 49;
Page({
	data: {
		goodsInfo: '',
		categoryStates: [],
		cartData: {},
		cartObjects: [],
		maskVisual: 'hidden',
		amount: 0,
		quantity: 2,
		num: 0,
		goods_id: '',
		indicatorDots: true, //是否显示面板指示点
		autoplay: true,
		interval: 2000, //自动切换时间间隔
		duration: 1000, //滑动动画时长
		indicatorColor: "rgba(255,255,255,.4)", //普通轮播点背景色
		indicatorActiveColor: "#fff", //选中轮播点背景色
		imgUrls: [],
		imgs: '',

	},
	//获取购物车
	getlists() {
		that = this;
		wx.request({
			url: App.url.requestUrl + 'Cart/getlists',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType: 'json',
			success: function(res) {
				if (res.data.ret == 200) {
					if (res.data.data.goods_list.length) {
						for (let i = 0; i < res.data.data.goods_list.length; i++) {
							if (that.data.goods_id == res.data.data.goods_list[i].goods_id) {
								that.setData({
									num: res.data.data.goods_list[i].total_num
								})
								console.log(res.data.data.goods_list[i].total_num)
							} 

						}

						that.setData({
							
							quantity: 2,
							cartinfo: res.data.data,
							cartObjects: res.data.data.goods_list
						})
					} else {
						that.setData({
							quantity: 0,
							cartObjects:[]
						})

					}

				}
			}
		})
	},
	//获取商品详情
	goodsInfo(id) {
		that = this;
		wx.request({
			url: App.url.requestUrl + 'index/goodsInfo',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType: 'json',
			data: {
				goods_id: id
			},
			success: function(res) {
				if (res.data.ret == 200) {
					//这里处理富文本
					if (res.data.data.content) {
					  //首先把图片格式化
					  res.data.data.content = res.data.data.content.replace(/<img src="\/uploads\//ig, "<img src=\"" +  App.url.requestUrl  + "\/uploads\/");
					  wxParse.wxParse('content', 'html', res.data.data.content, that, 0);
					
					}
					let imgarr=[]
					let img= res.data.data.images
					imgarr = img.split(","); // 用,分割
					console.log(imgarr)
					that.setData({
						goodsInfo: res.data.data,
						imgUrls:imgarr
					})
				}
			}
		})
	},
	onLoad: function(options) {
		that = this;
		that.setData({
			goods_id: options.id
		})
		that.getlists() //获取购物车
		that.goodsInfo(options.id) //获取商品详情

	},


	checkout: function() {
		// 将对象序列化
		var cartObjects = [];
		that.data.cartObjects.forEach(function(item, index) {
			console.log(item)
			console.log(index)
			var cart = {
				goods_id: item.goods_id,
				goods_num: item.total_num,
				// quantity: item.quantity
			};
			cartObjects.push(cart);
			console.log(cartObjects)
		});

		wx.navigateTo({
			url: '../../order/checkout/checkout?carts=' + JSON.stringify(cartObjects)
		});
	},
	add: function(e) {
		// 所点商品id
		// for (let i = 0; i < that.data.cartObjects.length; i++) {
		// 	that.data.cartObjects[i]
		// }

		var goods_id = e.currentTarget.dataset.foodId;
		var goods_num = e.currentTarget.dataset.num;
		console.log(goods_id);
		console.log(goods_num);
		++goods_num;
		that.cartToArrayadd(goods_id, goods_num);
	},
	subtract: function(e) {
		// 所点商品id
		var goods_id = e.currentTarget.dataset.foodId;
		var goods_num = e.currentTarget.dataset.num;
		--goods_num;
		if (goods_num >= 1) {
			that.cartToArraycut(goods_id);
		} else if (goods_num = 1) {
			that.dellgoods(goods_id);
		}

	},
	cartToArrayadd(goods_id, goods_num) {
		// 需要判断购物车数据中是否已经包含了原商品，从而决定新添加还是仅修改它的数量
		var cartData = that.data.cartData;
		var cartObjects = that.data.cartObjects;
		that = this;
		wx.request({
			url: App.url.requestUrl + 'Cart/add',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType: 'json',
			data: {
				goods_id: goods_id,
				goods_num: 1
			},
			success: function(res) {
				if (res.data.ret == 200) {
					that.getlists()
				}
			}
		})
	},
	cartToArraycut(goods_id) {
		// 需要判断购物车数据中是否已经包含了原商品，从而决定新添加还是仅修改它的数量
		var cartData = that.data.cartData;
		var cartObjects = that.data.cartObjects;
		that = this;
		wx.request({
			url: App.url.requestUrl + 'Cart/sub',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType: 'json',
			data: {
				goods_id: goods_id
			},
			success: function(res) {
				if (res.data.ret == 200) {
					that.getlists()
				}
			}
		})
	},
	dellgoods(goods_id) {
		var cartData = that.data.cartData;
		var cartObjects = that.data.cartObjects;
		that = this;
		wx.request({
			url: App.url.requestUrl + 'Cart/delete',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType: 'json',
			data: {
				goods_id: goods_id
			},
			success: function(res) {
				if (res.data.ret == 200) {
					that.getlists()
				}
			}
		})
	},


	cascadeToggle: function() {
		//切换购物车开与关
		// console.log(that.data.maskVisual);
		if (that.data.maskVisual == 'show') {
			that.cascadeDismiss();
		} else {
			that.cascadePopup();
		}
	},
	cascadePopup: function() {
		// 购物车打开动画
		var animation = wx.createAnimation({
			duration: 300,
			timingFunction: 'ease-in-out',
		});
		that.animation = animation;
		// scrollHeight为商品列表本身的高度
		var scrollHeight = (that.data.cartObjects.length <= max_row_height ? that.data.cartObjects.length : max_row_height) *
			food_row_height;
		// cartHeight为整个购物车的高度，也就是包含了标题栏与底部栏的高度
		var cartHeight = scrollHeight + cart_offset;
		animation.translateY(-cartHeight).step();
		that.setData({
			animationData: that.animation.export(),
			maskVisual: 'show',
			scrollHeight: scrollHeight,
			cartHeight: cartHeight
		});
		// 遮罩渐变动画
		var animationMask = wx.createAnimation({
			duration: 150,
			timingFunction: 'linear',
		});
		that.animationMask = animationMask;
		animationMask.opacity(0.8).step();
		that.setData({
			animationMask: that.animationMask.export(),
		});
	},
	cascadeDismiss: function() {
		// 购物车关闭动画
		that.animation.translateY(that.data.cartHeight).step();
		that.setData({
			animationData: that.animation.export()
		});
		// 遮罩渐变动画
		that.animationMask.opacity(0).step();
		that.setData({
			animationMask: that.animationMask.export(),
		});
		// 隐藏遮罩层
		that.setData({
			maskVisual: 'hidden'
		});
	},
	amount: function() {
		var cartObjects = that.data.cartObjects;
		var amount = 0;
		var quantity = 0;
		cartObjects.forEach(function(item, index) {
			amount += item.quantity * item.food.get('price');
			quantity += item.quantity;
		});
		that.setData({
			amount: amount.toFixed(2),
			quantity: quantity
		});
	},
	onShareAppMessage: function(res) {
		console.log(123)
		if (res.from === 'button') {
			// 来自页面内转发按钮
		}
		return {
			title: "这个小程序真好",
			path: 'pages/start/start?commentUserId=' + app.globalData.commentUserId
		}
	},
})
